<template>
  <div>
    <input type="file" ref="fileInput" style="margin-right: 12px" />
    <el-button type="primary" @click="upload">上传附件</el-button>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import type { AttachListItem } from '@/api/attachAPI'

const email_id = ref(0)
const id = localStorage.getItem('id') || ''
const token = localStorage.getItem('token') || ''

const fileInput = ref<HTMLInputElement>()

const uploadAttachmentAPI = async ():Promise<AttachListItem> => {
  const formData = new FormData()

  // console.log(file)
  console.log(id)
  console.log(token)
  console.log(email_id.value)

  formData.append('file', fileInput.value.files[0])
  formData.append('email_id', email_id.value.toString())
  axios.post('http://127.0.0.1:8000//api/attach/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
      'id': id,
      'token': token,
    },
  }).then(response => {
    console.log('上传成功', response.data.data);
  }).catch(error => {
    console.error('上传失败', error);
  });
}

const props = defineProps<{
  mail_id: number
}>()

email_id.value = props.mail_id

const upload = async () => {
  const files = fileInput.value?.files
  if (!files || files.length === 0) {
    ElMessage.warning('请选择文件')
    return
  }
  const file = files[0]
  // try {
    console.log(file)
    console.log(id)
    console.log(token)
    console.log(email_id.value)

    await uploadAttachmentAPI()

}
</script>
